/**
 * 子弹系统 - 管理子弹生命周期和清理
 */
import { System, World } from '../ecs';
import { Transform, Bullet } from '../components';

export class BulletSystem implements System {
  priority = 40;

  update(deltaTime: number, world: World): void {
    this.updateBulletLifetime(world, deltaTime);
    this.cleanupOffscreenBullets(world);
  }

  private updateBulletLifetime(world: World, deltaTime: number): void {
    const bullets = Array.from(world.entities).filter(e => e.hasComponent('bullet'));
    
    for (const bullet of bullets) {
      const bulletComponent = bullet.getComponent<Bullet>('bullet')!;
      
      bulletComponent.lifeTime += deltaTime;
      
      // 如果子弹超过生命周期，删除它
      if (bulletComponent.lifeTime >= bulletComponent.maxLifeTime) {
        world.removeEntity(bullet);
      }
    }
  }

  private cleanupOffscreenBullets(world: World): void {
    const { width, height } = world.resources;
    const bullets = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('bullet')
    );
    
    for (const bullet of bullets) {
      const transform = bullet.getComponent<Transform>('transform')!;
      
      // 如果子弹移出屏幕边界，删除它
      if (transform.x < -50 || transform.x > width + 50 || 
          transform.y < -50 || transform.y > height + 50) {
        world.removeEntity(bullet);
      }
    }
  }
}